<template>
   
    <div class="form-item">
        <div class="form-content">
       <div>
        <t-typography-title level="h3">注册到Light-IOT</t-typography-title>
       </div>
            
        
        <t-form ref="form" :data="formData" :label-width="0" @reset="onReset" @submit="onSubmit" :rules="rules" :status-icon="false">
            <t-form-item name="name">
                <t-input v-model="formData.name" clearable placeholder="请输入显示名称">
                <template #prefix-icon>
                    <UserIcon />
                </template>
                </t-input>
            </t-form-item>
            <t-form-item name="account">
                <t-input v-model="formData.account" clearable placeholder="请输入账户名">
                <template #prefix-icon>
                    <desktop-icon />
                </template>
                </t-input>
            </t-form-item>

            <t-form-item name="password">
                <t-input v-model="formData.password" type="password" clearable placeholder="请输入密码">
                <template #prefix-icon>
                    <lock-on-icon />
                </template>
                </t-input>
            </t-form-item>
            
            <t-form-item name="rePassword">
                <t-input v-model="formData.rePassword" type="password" clearable placeholder="请确认密码">
                <template #prefix-icon>
                    <lock-on-icon />
                </template>
                </t-input>
            </t-form-item>
            <t-form-item name="phone">
                <t-input v-model="formData.phone" clearable placeholder="请输入手机号">
                <template #prefix-icon>
                    <MobileIcon />
                </template>
                
                </t-input>
            </t-form-item>
            <t-form-item name="code">
                <t-input v-model="formData.code" clearable placeholder="请输入验证码">
                <template #prefix-icon>
                  <Code1Icon />
                </template>
                <template #suffixIcon>
                  <t-link hover="color" @click="getCode" :disabled="codeRef" theme="primary"> {{ codeMsg }} </t-link>
                </template>
                </t-input>
            </t-form-item>
            <t-form-item name="email">
                <t-auto-complete v-model="formData.email" :options="emailOptions" filterable clearable placeholder="请输入邮箱">
                <template #prefix-icon>
                    <MailIcon />
                </template>
            </t-auto-complete>
            </t-form-item>
        
            <t-form-item>
                <t-button theme="primary" type="submit" block>注册</t-button>
            </t-form-item>
        </t-form>
    
    </div>
    </div>
</template>
<style scoped>
.form-item{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
}
.form-content{
    width: 400px;
    background-color: #fff;
    padding: 10px 20px 40px 20px;
}
.phone-code{
    cursor: pointer;
    color: var(--td-brand-color-active);
    font-size: small;
}

</style>
<script setup>
import { DesktopIcon, LockOnIcon, MobileIcon, MailIcon,UserIcon,Code1Icon } from 'tdesign-icons-vue-next';
import { reactive,ref,computed } from 'vue';
import { register } from '@/api/api';
const form = ref()
const codeMsg = ref('获取验证码')
const codeRef = ref(false)
const formData = reactive({
    name:'',
  account: '',
  password: '',
  rePassword:'',
  phone:'',
  email:'',
  code:''
});

const onReset = () => {
  MessagePlugin.success('重置成功');
};

const onSubmit = ({ validateResult, firstError }) => {


  if (validateResult === true) {
    let data = {
      name:formData.name,
      account:formData.account,
      password:formData.password,
      phone:formData.phone,
      email:formData.email,
    }
    register(data).then(res=>{
      console.log(res)
    })
  } else {
    console.log('Validate Errors: ', firstError, validateResult);
   
  }
};

const emailSuffix = ['@qq.com', '@163.com', '@gmail.com'];
const emailOptions = computed(() => {
  const emailPrefix = formData.email.split('@')[0];
  if (!emailPrefix) return [];

  return emailSuffix.map((suffix) => emailPrefix + suffix);
});

const rePassword = (val) =>
  new Promise((resolve) => {
    const timer = setTimeout(() => {
      resolve(formData.password === val);
      clearTimeout(timer);
    });
  });

const checkPhone = (val) => {
  
  const regex = /^1[3-9]\d{9}$/;
  if(!regex.test(val)){
    return { result: false, message: '手机格式不正确', type: 'error' };
  }
  return { result: true};
}
  

  const checkAccount = (val) => new Promise((resolve)=>{
    
    const timer = setTimeout(()=>{
        resolve( true);
        clearTimeout(timer);
    });
  });

const rules = {
  name: [
    { required: true, message: '名称必填', type: 'error', trigger: 'blur' },
    { whitespace: true, message: '名称不能为空' },
  ],
  account: [
    { required: true, message: '账户必填', type: 'error', trigger: 'blur' },
    { whitespace: true, message: '账户不能为空' },
    { min: 4, message: '输入字数应在4到25之间', type: 'error', trigger: 'blur' },
    { max: 25, message: '输入字数应在4到25之间', type: 'error', trigger: 'blur' },
    { validator: checkAccount, message: '账户已经被注册'},
  ],
  password: [{ required: true, message: '密码必填', type: 'error' , trigger: 'blur'},
    { whitespace: true, message: '密码不能为空',trigger:'blur' },
    { min: 6, message: '密码字数应在6到12之间', type: 'error', trigger: 'blur' },
    { max: 12, message: '密码字数应在6到12之间', type: 'error', trigger: 'blur' },
  ],
  email: [{ required: true, message: '格式必须为邮箱', type: 'warning' },
  { email: { ignore_max_length: true } }
  ],
  rePassword: [
    // 自定义校验规则
    { required: true, message: '密码必填', type: 'error' },
    { validator: rePassword, message: '两次密码不一致' },
  ],
  phone:[{ required: true, message: '手机必填', type: 'error', trigger: 'blur'},
  { validator: checkPhone,},
  ]
};

const getCode = () => {

  //发送请求，当返回为失败，则
  
    console.log('点击了')
    // form.value.setValidateMessage(
    //   {
    //     phone: [
    //     {
    //       type: 'error',
    //       message: '手机号已经被注册',
    //     },
    //   ],
    //   }
    // )
    var count = 60;
    codeRef.value = true
    var time = setInterval(()=>{
      codeMsg.value = count+'s后重新获取'
      --count
      if(count<0){
        clearInterval(time)
        codeRef.value = false
        codeMsg.value = '获取验证码'
      }
    },1000)
}
</script>